package hdelies

import (
	"article-reader/cache"
	"article-reader/models"
	"article-reader/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

// 登录
func Login(c *gin.Context) {
	name := c.PostForm("name")
	passes := c.PostForm("passes")

	var user models.User
	err := models.DB.Where("name=?", name).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Passes != pkg.Md5(passes) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

// 添加
func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	are := c.PostForm("are")

	if title == "" || content == "" || are == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Ares{
		Title:   title,
		Content: content,
		Are:     are,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "redis_add" + strconv.Itoa(int(data.ID))
	var ares models.Ares
	models.DB.Where("id=?", data.ID).First(&ares)
	jsonAdd, _ := json.Marshal(ares)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonAdd, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

// 详情
func XoiRng(c *gin.Context) {
	id := c.Query("id")
	var ares models.Ares
	err := models.DB.Where("id=?", id).First(&ares).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": ares,
	})
	return
}

// 删除
func Del(c *gin.Context) {
	id := c.Query("id")

	redis_key := "redis_add" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	models.DB.Where("id=?", id).Delete(&models.Ares{})
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

// 列表
func List(c *gin.Context) {
	var po []models.Ares

	redis_key := "redis_liat"
	jsonList, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if jsonList == "" {
		models.DB.Find(&po)
		JSONLint, _ := json.Marshal(po)
		cache.Rdb.Set(cache.Ctx, redis_key, JSONLint, time.Hour*2)
	} else {
		json.Unmarshal([]byte(jsonList), &po)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": po,
	})
	return
}
